from osv import osv, fields
from osv.orm import intersect
import time

#Red Invoice
class kdvn_purchase_red_invoice(osv.osv):
    _name="kdvn.purchase.red.invoice"
    _description="KDVN Purchase Red Invoice Information"    
    _columns={
             'name':fields.char('Invoice No.',size=16,required=True),
             'date':fields.date('Date'),
             'type':fields.selection([('in_invoice','Supplier'),('out_invoice','Customer')],'Type',select=True),
             'job_type': fields.selection([('E','Electrical'),('M','Mechanical'),('ME','M&E')],'Job type', select=True),
             'currency_id':fields.many2one('kdvn.purchase.currency','Currency'),
             'received_date':fields.date('Received Date',states={'completed':[('readonly',True)]}),
             'to_accounting_date':fields.date('To Accounting Date',states={'completed':[('readonly',True)]}),
             'returned_date':fields.date('Returned Date',states={'completed':[('readonly',True)]}),
             'subtotal':fields.float('Sub-Total'),
             'tax_percent':fields.float('VAT (%)'),
             'amount_tax':fields.float('Tax'),
             'total_amount':fields.float('Total'),
             'rate':fields.float('@'),
             'equivalent_vnd':fields.float('Equivalent VND',digits=(16,0)),            
             'notes':fields.text('Notes'),
             }
    _defaults={
               'type':lambda *x: 'in_invoice',
               'subtotal':lambda *x:0.0,
               'tax_percent':lambda *x:0.0,
               'amount_tax':lambda  *x:0.0,
               'total_amount':lambda *x:0.0,
               'equivalent_vnd':lambda *x:0.0,
               'rate':lambda *x:1,
               }
    
    def _onchange_totalamount(self,cr,uid,ids,total_amount,type,currency_id,date,kdvn_check,rate,equivalent_vnd):
        result={}
         # Bien dung de check xem goi tu form hay tu view hay code
        if type=='currency_id':            
            curr_id = currency_id
            rate=0
            if curr_id:
                if not date:
                    date=time.strftime('%Y-%m-%d')                                                        
                cr.execute("SELECT rate FROM kdvn_purchase_currency_rate WHERE kdvn_purchase_currency_id = %s AND name <='%s'::date LIMIT 1" %(curr_id, date))
                #kdvn_po_rate_obj = self.pool.get('kdvn.purchase.currency').compute(cr,uid,curr_id,curr_id,1,False,context)
                kdvn_po_rate_obj = cr.fetchone()
                if kdvn_po_rate_obj:
                    rate = kdvn_po_rate_obj[0]
            result={'rate':rate,'equivalent_vnd':total_amount*rate}
        elif total_amount==0:
            result={'rate':1}
        elif type=='total_amount':
            result={'equivalent_vnd':total_amount*rate}
        elif type=='equivalent_vnd':
            new_rate = 0.0
            if total_amount>0:
                new_rate = equivalent_vnd / total_amount
            result={'rate':new_rate}
        elif type=='rate':
            result={'equivalent_vnd':rate*total_amount}
        
        if kdvn_check:        
            return {'value':result}
        else:
            return result

    def _on_changevalue(self,cr,uid,ids,amount,tax_percent,amount_tax,date,rate):
        if amount_tax==False:
            amount_tax=amount*tax_percent/100.0
            total_amount=amount+amount_tax
            result={'amount_tax':amount_tax,'total_amount':total_amount}
        else:
            total_amount=amount+amount_tax
            result={'amount_tax':amount_tax,'total_amount':total_amount}
        result2 = self._onchange_totalamount(cr,uid,ids,total_amount,'total_amount',False,date,False,rate,False)
        result.update(result2)
        return {'value':result}
    
kdvn_purchase_red_invoice()